package com.chenc.javathreads.TestJavaLock.synchronizegetballs;

import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName
 * @Describtion:
 * @Author:Chenc
 * @Date:2023/11/23 17:49
 * @Version 1.0
 */
public class GetBalls {

    private static Integer Millions = 10000;
    private static List<String> allBalls = new ArrayList<>();

    static class RobBall{
        static List<String> result = new ArrayList<>();
        static HashMap<Long,List<String>> threadReslultMap = new HashMap<>();
        public void getBall(){
            for (int i = 0; i < Millions; i++) {
                synchronized (this){
                    long id = Thread.currentThread().getId();
                    if (allBalls.size()<=0){
                        break;
                    }
                    String obj= allBalls.get(0);
                    result.add(obj);
                    allBalls.remove(obj);
                    putResult(id, obj);
                }
            }
            print();

        }
        private List<String> putResult(Long thread,String currentnum){
            List<String> strings = threadReslultMap.get(thread);
            if (CollectionUtils.isEmpty(strings)){
                ArrayList<String> strings1 = new ArrayList<String>() {{
                    add(currentnum);
                }};
                threadReslultMap.put(thread,strings1);
                return strings1;
            }else{
                strings.add(currentnum);
                threadReslultMap.put(thread,strings);
                return strings;
            }
        }

        private void print(){
            long id = Thread.currentThread().getId();
            List<String> strings = threadReslultMap.get(id);
            System.out.println("大小:"+strings.size()+"线程'"+id+"'结果:"+strings);
        }

    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < Millions; i++) {
            allBalls.add(String.valueOf(i));
        }
        RobBall robBall = new RobBall();
        Thread thread1 = new Thread(() -> {
            robBall.getBall();
        });
        thread1.start();
        Thread thread2 = new Thread(() -> {
            robBall.getBall();
        });
        Thread thread3 = new Thread(() -> {
            robBall.getBall();
        });
        thread2.start();
        thread3.start();
        thread1.join();
        thread2.join();
        thread3.join();


    }
}
